package com.yztc.love_travel.ui.main;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jude.rollviewpager.RollPagerView;
import com.yztc.love_travel.R;
import com.yztc.love_travel.adater.ADAdapter;
import com.yztc.love_travel.adater.MainAdapter;
import com.yztc.love_travel.bean.WeatherBean;
import com.yztc.love_travel.bean.homepage.BaseBean;
import com.yztc.love_travel.bean.homepage.FourTripBean;
import com.yztc.love_travel.bean.homepage.MainServiceBean;
import com.yztc.love_travel.bean.homepage.NextStopBean;
import com.yztc.love_travel.bean.homepage.RecommendTripNotesBean;
import com.yztc.love_travel.constant.URLConstant;
import com.yztc.love_travel.helper.baidumap.ILocationListener;
import com.yztc.love_travel.helper.baidumap.MapLocation;
import com.yztc.love_travel.helper.decoration.SpacesItemDecoration;
import com.yztc.love_travel.ui.recommondtripnotes.presenter.IRecommendTripNotesPresenter;
import com.yztc.love_travel.ui.recommondtripnotes.presenter.RecommendTripNotesPresenterImpl;
import com.yztc.love_travel.ui.recommondtripnotes.view.IRecommendTripNotesView;
import com.yztc.love_travel.utils.WeatherUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity implements IRecommendTripNotesView,ILocationListener{

    private static final int[] IMAGES_MAIN_SERVICE = {
            R.mipmap.home_lishiwenhua,
            R.mipmap.home_jingdiangonglue,
            R.mipmap.home_wdd,
            R.mipmap.home_cms,
            R.mipmap.home_zjd,
            R.mipmap.home_hlg
    };

    private static final int[] IMAGES_FOUR_TRIP = {
            R.drawable.religion_culture,
            R.drawable.culture_trip,
            R.drawable.romantic,
            R.drawable.story_trip,
    };

    @BindView(R.id.rollPagerView)
    RollPagerView rollViewPager; //轮播的广告
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.imageview_main)
    ImageView imageviewMain;
    @BindView(R.id.imageview_login_main)
    ImageView imageviewLoginMain;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.toolbar_layout)
    CollapsingToolbarLayout toolbarLayout;
    @BindView(R.id.app_bar)
    AppBarLayout appBar;
    @BindView(R.id.textview_search)
    TextView textviewSearch;

    @BindView(R.id.textView_city)
    TextView textViewCity;
    @BindView(R.id.textView_today)
    TextView textViewToday;
    @BindView(R.id.textView_currentTemp)
    TextView textViewCurrentTemp;
    @BindView(R.id.imageView_weatherIcon)
    ImageView imageViewWeatherIcon;
    @BindView(R.id.textView_weatherTemp)
    TextView textViewWeatherTemp;
    @BindView(R.id.textView_weatherWind)
    TextView textViewWeatherWind;
    @BindView(R.id.textView_weatherState)
    TextView textViewWeatherState;
    @BindView(R.id.textView_ganmao)
    TextView textViewGanmao;
    @BindView(R.id.layout_current)
    LinearLayout layoutCurrent;

    //定义天气预告信息的数据集合
    private List<WeatherBean.DataEntity.ForecastEntity> mTotalList = new ArrayList<>();
    private AlertDialog alertDialog; //提示是否退出应用的对话框
    private Context mContext;
    private List<BaseBean> mList; //RecyclerView的数据源
    private MainAdapter mainAdapter; //适配器
    private IRecommendTripNotesPresenter mPresenter;
    private Activity activity; //调用百度地图定位所需的参数



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        mContext = this;
        activity = this;

        getLocationData(); //获取百度地图定位的地址的结果
        initPresenter();
        loadTripNotesData();
        showAD();
        initRecyclerViewData();
        initRecyclerView();
        initDialog();

    }

    //获取定位地址的结果
    private void getLocationData(){
        MapLocation mapLocation = new MapLocation(activity,this);
        mapLocation.getAddress(); //获取定位的地址，在接口回调处接受
    }

//退出程序处理
    private void initDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("亲,再逛会儿吧!")
                .setView(R.layout.dialog_exit)
                .setCancelable(true)
                .setPositiveButton("退出", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                })
                .setNegativeButton("再看看", null);
        alertDialog = builder.create();
    }
    //监听退出键
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            alertDialog.show();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }


    /**
     * 将天气信息展示在UI控件上
     *
     * @param dataEntity
     */
    private void showWeatherInfo(WeatherBean.DataEntity dataEntity) {
        //获取城市名称
        textViewCity.setText(dataEntity.getCity());
        //获取感冒指数
        textViewGanmao.setText(dataEntity.getGanmao());
        //加载当天的天气信息
        textViewToday.setText(mTotalList.get(0).getDate());
        //获取当前温度
        textViewCurrentTemp.setText(dataEntity.getWendu() + "℃");

        textViewWeatherTemp.setText(mTotalList.get(0).getHigh() + "\r\n"
                + mTotalList.get(0).getLow());
        textViewWeatherWind.setText("风力："
                + mTotalList.get(0).getFengli() + "\r\n风向："
                + mTotalList.get(0).getFengxiang());

        String weatherType = mTotalList.get(0).getType();
        //根据天气类型获取相应的icon图标
        textViewWeatherState.setText(weatherType);
        imageViewWeatherIcon.setImageResource(getWeatherIcon
                (weatherType).get(1));
        String content = dataEntity.getCity() + mTotalList.get(0).getType
                () + dataEntity.getWendu() + "℃" + mTotalList.get(0)
                .getHigh() + "\r\n"
                + mTotalList.get(0).getLow() + "风力："
                + mTotalList.get(0).getFengli() + "\r\n风向："
                + mTotalList.get(0).getFengxiang() + dataEntity.getGanmao();
    }


    /**
     * 根据天气状态返回有关天气图片的id
     * @param weather
     * @return
     */
    private List<Integer> getWeatherIcon(String weather) {
        List<Integer> list = new ArrayList<>();
        if (weather.equals("多云") || weather.equals("多云转阴") || weather.equals("多云转晴")) {
            list.add(R.drawable.bg_cloudy);
            list.add(R.mipmap.biz_plugin_weather_duoyun);
        } else if (weather.equals("中雨") || weather.equals("中到大雨")) {
            list.add(R.drawable.bg_rain);
            list.add(R.mipmap.biz_plugin_weather_zhongyu);
        } else if (weather.equals("雷阵雨")) {
            list.add(R.drawable.bg_thunder_storm);
            list.add(R.mipmap.biz_plugin_weather_leizhenyu);
        } else if (weather.equals("阵雨") || weather.equals("阵雨转多云")) {
            list.add(R.drawable.bg_rain);
            list.add(R.mipmap.biz_plugin_weather_zhenyu);
        } else if (weather.equals("暴雪")) {
            list.add(R.drawable.bg_snow_yin);
            list.add(R.mipmap.biz_plugin_weather_baoxue);
        } else if (weather.equals("暴雨")) {
            list.add(R.drawable.bg_rain);
            list.add(R.mipmap.biz_plugin_weather_baoyu);
        } else if (weather.equals("大暴雨")) {
            list.add(R.drawable.bg_rain);
            list.add(R.mipmap.biz_plugin_weather_dabaoyu);
        } else if (weather.equals("大雪")) {
            list.add(R.drawable.bg_snow_yin);
            list.add(R.mipmap.biz_plugin_weather_daxue);
        } else if (weather.equals("大雨") || weather.equals("大雨转中雨")) {
            list.add(R.drawable.bg_rain);
            list.add(R.mipmap.biz_plugin_weather_dayu);
        } else if (weather.equals("雷阵雨冰雹")) {
            list.add(R.drawable.bg_rain);
            list.add(R.mipmap.biz_plugin_weather_leizhenyubingbao);
        } else if (weather.equals("晴")) {
            list.add(R.drawable.bg_sunny);
            list.add(R.mipmap.biz_plugin_weather_qing);
        } else if (weather.equals("沙尘暴")) {
            list.add(R.drawable.bg_sand_storm);
            list.add(R.mipmap.biz_plugin_weather_shachenbao);
        } else if (weather.equals("特大暴雨")) {
            list.add(R.drawable.bg_rain);
            list.add(R.mipmap.biz_plugin_weather_tedabaoyu);
        } else if (weather.equals("雾") || weather.equals("霾") || weather.equals("雾霾")) {
            list.add(R.drawable.bg_fog);
            list.add(R.mipmap.biz_plugin_weather_wu);
        } else if (weather.equals("小雪")) {
            list.add(R.drawable.bg_snow);
            list.add(R.mipmap.biz_plugin_weather_xiaoxue);
        } else if (weather.equals("小雨")) {
            list.add(R.drawable.bg_rain);
            list.add(R.mipmap.biz_plugin_weather_xiaoyu);
        } else if (weather.equals("阴")) {
            list.add(R.drawable.bg_overcast);
            list.add(R.mipmap.biz_plugin_weather_yin);
        } else if (weather.equals("雨夹雪")) {
            list.add(R.drawable.bg_snow);
            list.add(R.mipmap.biz_plugin_weather_yujiaxue);
        } else if (weather.equals("阵雪")) {
            list.add(R.drawable.bg_snow);
            list.add(R.mipmap.biz_plugin_weather_zhenxue);
        } else if (weather.equals("中雪")) {
            list.add(R.drawable.bg_snow);
            list.add(R.mipmap.biz_plugin_weather_zhongxue);
        } else {
            list.add(R.drawable.bg_cloudy);
            list.add(R.mipmap.biz_plugin_weather_duoyun);
        }
        return list;
    }



    //加载"推荐游记列表"的数据
    private void loadTripNotesData() {
        Map<String, Object> params = new HashMap<>();
        params.put(URLConstant.RecommendNotes.TRIPSTREETID, 3);
        params.put(URLConstant.RecommendNotes.STATUS, 1);
        params.put(URLConstant.RecommendNotes.ISRELEASESTREET, 1);
        params.put(URLConstant.RecommendNotes.PAGENO, 0);
        params.put(URLConstant.RecommendNotes.PAGESIZE, 20);
        mPresenter.getRecommendTripNotes(URLConstant.RecommendNotes.URL_RECOMMEND_BASE, params);
    }

    private void initPresenter() {
        mPresenter = new RecommendTripNotesPresenterImpl(this);
    }

    //初始化RecyclerView
    private void initRecyclerView() {
        mainAdapter = new MainAdapter(mContext, mList);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 6, OrientationHelper.VERTICAL, false);
        recyclerView.addItemDecoration(new SpacesItemDecoration(2));
        //为不同类型的Item设置不同的布局管理器
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                int type = mList.get(position).getType();
                switch (type) {
                    case 1:
                        //主要服务
                        return 2;
                    case 2:
                        //推荐的4个旅游路线
                        return 3;
                    case 3:
                        //发现下一站
                        return 6;
                    case 4:
                        return 6;
                    default:
                        return 0;
                }
            }
        });
        recyclerView.setAdapter(mainAdapter);
        recyclerView.setLayoutManager(gridLayoutManager);

    }

    //初始化RecyclerView的数据
    private void initRecyclerViewData() {
        mList = new ArrayList<>();
        String[] mainServiceTitles = getResources().getStringArray(R.array.main_service_title);
        for (int i = 0; i < mainServiceTitles.length; i++) {
            MainServiceBean mainServiceBean = new MainServiceBean(IMAGES_MAIN_SERVICE[i], mainServiceTitles[i]);
            mainServiceBean.setType(1); //设置类型为1
            mList.add(mainServiceBean);
        }

        String[] fourTripTitles = getResources().getStringArray(R.array.four_trip_title);
        for (int i = 0; i < fourTripTitles.length; i++) {
            FourTripBean fourTripBean = new FourTripBean(IMAGES_FOUR_TRIP[i], fourTripTitles[i]);
            fourTripBean.setType(2);//设置类型为2
            mList.add(fourTripBean);
        }

        NextStopBean nextStopBean = new NextStopBean();
        nextStopBean.setType(3); //设置类型为3
        mList.add(nextStopBean);
    }


    //显示轮播的广告
    private void showAD() {
        rollViewPager.setAdapter(new ADAdapter(mContext, rollViewPager));
    }

    //加载数据失败
    @Override
    public void loadError() {

    }

    //显示加载成功的"推荐游记"的数据
    @Override
    public void showData(RecommendTripNotesBean recommendTripNotesBean) {
        List<RecommendTripNotesBean.ManualArticleListBean> manualArticleList = recommendTripNotesBean.getManualArticleList();
        for (int i = 0; i < manualArticleList.size(); i++) {
            //图片地址
            RecommendTripNotesBean.ManualArticleListBean manualArticleListBean = manualArticleList.get(i);
            manualArticleListBean.setType(4); //设置类型为4
            mList.add(manualArticleListBean);
        }
        mainAdapter.notifyDataSetChanged();
    }

    @Override
    public void showWeather(WeatherBean weatherBean) {
        if (weatherBean.getDesc().equals("OK")) {
            WeatherBean.DataEntity dataEntity = weatherBean.getData();
            if (dataEntity != null) {
                mTotalList = dataEntity.getForecast();
                //将天气信息显示在UI控件上
                showWeatherInfo(dataEntity);
            }
        }
    }

    @OnClick({R.id.imageview_main, R.id.imageview_login_main})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imageview_main:
                break;
            case R.id.imageview_login_main:
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, MyActivity.class);
                startActivity(intent);
                break;
        }
    }


    @Override
    public void getAddress(String address) {}

    //获取百度定位的"城市"的结果
    @Override
    public void getCity(String city) {
        WeatherUtils weatherUtils = new WeatherUtils(MainActivity.this,city,this);
        weatherUtils.getWeatherBean(); //获取天气预报的结果
    }
}
